package com.house.java.biz;

import java.util.List;

import org.apache.log4j.Logger;

import com.house.java.dao.DaoFactory;
import com.house.java.dao.UserDAO;
import com.house.java.dao.impl.UserDaoImpl;
import com.house.java.model.Paging;
import com.house.java.model.User;

public class UserBusiness {

	private static Logger log = Logger.getLogger(UserBusiness.class);
	private UserDAO dao = (UserDaoImpl)DaoFactory.getDaoImpl(UserDAO.class);
	
	/**
	 * 添加用户
	 * @param user
	 * 
	 * exist 	--->  存在该用户
	 * success	--->  添加成功
	 * fail		--->  添加失败
	 */
	public String addUser(User user){
		if(null != user){
			if(null != user.getId()){
				update(user);
			}else {
				List<User> list = queryUsers(null, user.getUserName(), null);
				if(null != list && list.size() > 0){
					log.error("exist user,the name is "+user.getUserName());
					return "exist";
				}
				dao.addUser(user);
				if(null != user.getId()){
					return "success";
				}
				return "fail";
			}
		}
		return "fail";
	}
	
	public boolean update(User user){
		List<User> list = dao.queryUserByUserName(user.getId(), null, null);
		if(null != list && list.size()>0 ){
			int result = dao.delete(list.get(0).getId());
			if(result>0){
				dao.addUser(user);
				return true;
			}else {
				return false;
			}
		}
		return false;
	}
	
	/**
	 * 查询用户列表，支持用户名模糊查询
	 * @param userName
	 * @param paging
	 * @return
	 */
	public List<User> queryUsers(Long id,String userName,Paging paging){
		return dao.queryUserByUserName(id, userName, paging);
	}
	
	
	public List<User> queryUsers(User user,Integer currentPage, Integer pageSize){
		return queryUsers(user.getId(), user.getUserName(),buildPaging(currentPage, pageSize));
	}
	
	private Paging buildPaging(Integer currentPage, Integer pageSize){
		if(null != currentPage && null != pageSize){
			return null;
		}
		Paging paging = new Paging();
		paging.setCurrentPage(currentPage);
		paging.setPageSize(pageSize);
		return paging;
	}
	/**
	 * 用户登录业务
	 * @param user
	 */
	public boolean login(User user){
		List<User> users = queryUsers(user.getId(),user.getUserName(), null);
		if(null != users && users.size() == 1){
			User loginUser = users.get(0);
			if(loginUser.getPassword().equals(user.getPassword())){
				return true;
			}else {
				log.error("the password is wrong");
			}
		}else {
			log.error(" not find the user:"+user.getUserName());
		}
		return false;
	}
}
